package cn.edu.jdbc.util;

import org.junit.Test;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;


    /**
     * 文件的读取，只需要读取一次就可以取到这些值。使用静态代码块。
     */
    static {
        //创建Properties集合类
        Properties pro = new Properties();
        //获取文件的路径
        ClassLoader classLoader = JdbcUtil.class.getClassLoader();
        URL res = classLoader.getResource("jdbc.properties");
        String path = res.getPath();
//        System.out.println(path);
        try {
            //加载文件
            pro.load(new FileReader(path));

            //获取数据，赋值
            url = pro.getProperty("jdbc.url");
            user = pro.getProperty("jdbc.user");
            password = pro.getProperty("jdbc.password");
            driver = pro.getProperty("jdbc.driver");

            //注册驱动
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接数据库
     * @return
     * @throws SQLException
     */
    public static Connection getConn() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }

    /**
     * 关闭资源
     * @param st
     * @param conn
     */
    public static void close(Statement st, Connection conn){
        if (st != null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭资源
     * @param rs
     * @param st
     * @param conn
     */
    public static void close(ResultSet rs, Statement st, Connection conn){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testConn() throws SQLException {
        Connection conn = JdbcUtil.getConn();
        System.out.println(conn);
    }


}
